﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Reflection;
using System.Text;

namespace WFL.Data.SqlClient
{
    public class SqlConnectionProxy : ConnectionProxy, IConnectionProxy
    {
        internal SqlConnection Connection 
        { 
            get; 
            private set;
        }

        internal SqlTransactionProxy TransactionProxy 
        { 
            get; 
            set; 
        }

        public SqlConnectionProxy(SqlConnection connection, string connectionString)
        {
            Connection = connection;
            ConnectionString = connectionString;
        }

        protected ITransactionProxy OnBeginTransaction(IsolationLevel iso)
        {
            if (TransactionProxy == null)
            {
                TransactionProxy = new SqlTransactionProxy(Connection.BeginTransaction(iso));
                TransactionProxy.ConnectionProxy = this;
                TransactionProxy.CreatingMethod = new StackFrame(2).GetMethod();
            }
            else
            {
                if (TransactionProxy.Transaction.IsolationLevel != iso)
                {
                    throw new Exception("上下文中存在不同隔离级别的事务");
                }
            }
            return TransactionProxy;
        }


        #region IConnectionProxy 成员

        public string ConnectionString
        {
            get;
            private set;
        }

        public ConnectionState State
        {
            get { return Connection.State; }
        }

        public void Close()
        {
            MethodBase callingMethod = new StackFrame(1).GetMethod();
            if (callingMethod == base.CreatingMethod)
            {
                Connection.Close();
            }
        }

        public ITransactionProxy BeginTransaction(IsolationLevel iso)
        {
            return OnBeginTransaction(iso);
        }

        public ITransactionProxy BeginTransaction()
        {
            return OnBeginTransaction(IsolationLevel.ReadCommitted);
        }

        #endregion

    }
}
